/*
 * Copyright 2012 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.android.calllog.dao;

import nl.biz_e.android.calllog.CallLogApp;
import nl.biz_e.android.calllog.model.CallLogItem;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;

/**
 * TODO: Write type comment
 * 
 * @author Joost A. Bloemsma
 */
class ContactDao {
	private static final String DEBUG_TAG = ContactDao.class.getSimpleName();
	private Context _ctx;
	private static ContactDao _instance = null;
	
	private ContactDao(Context ctx) {
		super();
		this._ctx = ctx;
	}
	
	/**
	 * Factory method. Makes sure this is a singleton.
	 * @return Instance of this DAO
	 */
	public static ContactDao getInstance() {
		if (_instance == null) {
			_instance = new ContactDao(CallLogApp.getAppContext());
		}
		return _instance;
	}
	
	public void addContactData(CallLogItem itm) {
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(itm.getNumber()));
		ContentResolver resolver = _ctx.getContentResolver();
		@SuppressWarnings("static-access")
		Cursor cur = resolver.query(uri, new String[]{PhoneLookup.LOOKUP_KEY, PhoneLookup._ID}, null, null, null);
		if (cur.moveToFirst()) {
			itm.setContactLookupKey(cur.getString(0));
			itm.setContactId(cur.getInt(1));
			if (Log.isLoggable(DEBUG_TAG, Log.DEBUG)) Log.d(DEBUG_TAG, "Got contactinfo for item " + itm.getItemId());
		}
		cur.close();
	}
	
	}

